<?php


namespace App\Http\Controllers\Admin;


use App\Models\Appoint;
use App\Models\TimeConfig;
use App\Services\AppointService;
use App\Services\ConfigService;
use Dingo\Api\Http\Request;

class AppointController extends BaseController
{

    public function index(Request $request) {
        $input = $request->input();

        $query = Appoint::join('users', function ($join) use($input) {
            $query = $join->on('users.id', '=', 'appoints.user_id');
            if (!empty($input['realname'])) {
                $query->where('appoints.realname', 'like', '%' . $input['realname'] . "%");
            }
            if (!empty($input['phone'])) {
                $query->where('appoints.phone', $input['phone']);
            }
            return $query;
        })->join('heros', function ($join) use($input)  {
            $query = $join->on('appoints.hero_id', '=', 'heros.id');
            return $query;
        });
        if (!empty($input['date'])) {
            $query = $query->where('date', '=', $input['date']);
        }
        if (!empty($input['time'])) {
            $query = $query->where('time', '=', $input['time']);
        }
        $list = $query->select('appoints.realname', 'users.nickname', 'appoints.phone', 'heros.username as hero_username'
                , 'heros.area', 'heros.row', 'heros.seat', 'appoints.date', 'appoints.time', 'appoints.order_no', 'appoints.id')
            ->paginate(\request('per_page', 20));

        return $this->paginate($list);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'id' => 'required|exists:appoints'
        ]);
        $id = \request("id");
        $appoint = Appoint::find($id);
        \Log::error($appoint->toArray());
        $order_no = substr($appoint->order_no, -4, 4);
        $order_no = intval($order_no);
        $key = TimeConfig::where('value', $appoint->time)->value('key');
        $ret = AppointService::insertOrderNoToCache($order_no, $appoint->date, $key);
        $appoint->delete();
        return $this->success($ret);
    }

    public function timeRange() {
        $ret = ConfigService::getAll();
        return $this->success($ret);
    }

}

